package com.squirrel.common.util;

import com.squirrel.common.exception.BaseException;
import com.squirrel.common.response.code.CodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import java.io.IOException;

/**
 * @Description LoginByPhoneUtils 手机号登录工具类
 * @Author 关远键
 * @Version v1.0.0
 * @Date 2021/11/24 10:17
 */
@Slf4j
public class LoginByPhoneUtils {

    private static final String URL = "http://106.ihuyi.com/webservice/sms.php?method=Submit";
    private static final String ACCOUNT = "C99000330";
    private static final String PASSWORD = "60fcfb491660e64583cd50dc5ae9db86";

    /**
     * 发送手机验证码并返回（要钱的啊，慎用！慎用！慎用！）
     * @author 关远键
     * @date 2021/11/28 22:44
     * @param phone 手机号
     * @return java.lang.Integer
     */
    public static synchronized Integer sendAndGet(String phone) {

        HttpClient client = new HttpClient();
        PostMethod method = new PostMethod(URL);

        client.getParams().setContentCharset("GBK");
        method.setRequestHeader("ContentType","application/x-www-form-urlencoded;charset=GBK");

        int mobileCode = (int)((Math.random()*9+1)*100000);

        String content = "您的验证码是：" + mobileCode + "。请不要把验证码泄露给其他人。";
        log.info("发送给【{}】的手机短信验证的内容：{}", phone, content);

        // 测试使用，部署放开注释代码
//        return mobileCode;

        //提交短信
        NameValuePair[] data = {
                new NameValuePair("account", ACCOUNT),
                new NameValuePair("password", PASSWORD),
                //new NameValuePair("password", util.StringUtil.MD5Encode("密码")),
                new NameValuePair("mobile", phone),
                new NameValuePair("content", content),
        };
        method.setRequestBody(data);

        try {
            // 发送短信
            client.executeMethod(method);


            String SubmitResult =method.getResponseBodyAsString();

            //System.out.println(SubmitResult);

            Document doc = DocumentHelper.parseText(SubmitResult);
            Element root = doc.getRootElement();

            String code = root.elementText("code");
            String msg = root.elementText("msg");
            String smsid = root.elementText("smsid");

            log.info("手机验证code:{}", code);
            log.info("手机验证msg:{}", msg);
            log.info("手机验证smsid:{}", smsid);

            if("2".equals(code)){
                log.info("成功给【{}】发送手机短信", phone);
            }

            return mobileCode;

        } catch (IOException | DocumentException e) {
            e.printStackTrace();
        }

        throw new BaseException(CodeEnum.PHONE_ERROR);
    }
}
